package com.cyt.work.enrollment.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.BaseConstant;
import com.cyt.base.util.BaseUtil;
import com.cyt.base.util.DictCode;
import com.cyt.base.util.ErrorCode;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.service.SysFileService;
import com.cyt.sys.service.impl.BaseServiceImpl;
import com.cyt.sys.util.EasyPoiUtil;
import com.cyt.sys.util.FilePathUtil;
import com.cyt.sys.util.GlobalExcelDictHandler;
import com.cyt.work.enrollment.dao.EnrollmentRuleDao;
import com.cyt.work.enrollment.model.po.EnrollmentRule;
import com.cyt.work.enrollment.model.vo.EnrollmentRuleImportVo;
import com.cyt.work.enrollment.model.vo.EnrollmentRuleVerifyImportVo;
import com.cyt.work.enrollment.model.vo.EnrollmentRuleVo;
import com.cyt.work.enrollment.service.EnrollmentRuleService;
import com.cyt.wx.model.vo.WxEducationUserImportVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

/**
 * 自主招生-招生章程Service层实现类
 *
 * @author caideyong
 * @date 2019-11-22 16:21:03
 */
@Service("enrollmentRuleService")
public class EnrollmentRuleServiceImpl extends BaseServiceImpl<EnrollmentRule> implements EnrollmentRuleService {

    @Resource
    private EnrollmentRuleDao enrollmentRuleDao;

    @Autowired
    private SysFileService sysFileService;

    @Autowired
    public void setBaseDao(EnrollmentRuleDao enrollmentRuleDao) {
        this.baseDao = enrollmentRuleDao;
    }

    /**
     * 查询对象集合
     *
     * @param enrollmentRuleVo 对象
     * @return List 对象集合
     * @author caideyong
     * @date 2019-11-22 16:21:03
     */
    @Override
    public List<EnrollmentRule> listExample(EnrollmentRuleVo enrollmentRuleVo) {
        return enrollmentRuleDao.getEnrollmentRuleList(enrollmentRuleVo);
    }

    /**
     * 分页查询
     *
     * @param enrollmentRuleVo 接受参数对象
     * @param pageNum          分页数
     * @param pageSize         每页显示条数
     * @return ReturnResult
     * @author caideyong
     * @date 2019-11-22 16:21:03
     */
    @Override
    public ReturnResult page(EnrollmentRuleVo enrollmentRuleVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" create_time desc");
        List<EnrollmentRule> list = listExample(enrollmentRuleVo);
        PageInfo<EnrollmentRule> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    /**
     * 添加或更新
     *
     * @param enrollmentRuleVo 参数接受对象
     * @param sysUser          当前用户
     * @return ReturnResult
     * @author caideyong
     * @date 2019-11-22 16:21:03
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(EnrollmentRuleVo enrollmentRuleVo, SysUser sysUser) {
        //判断主键id是否存在,如果存在就更新,否则新建
        if (StringUtils.isBlank(enrollmentRuleVo.getId())) {
            EnrollmentRule enrollmentRule = new EnrollmentRule(sysUser);
            enrollmentRule.setName(enrollmentRuleVo.getName());
            enrollmentRule.setUnit(enrollmentRuleVo.getUnit());
            enrollmentRule.setUseNum(0);//新建时使用次数置为0
            enrollmentRule.setIntroduction(enrollmentRuleVo.getIntroduction());
            enrollmentRule.setCreator(sysUser.getId());
            enrollmentRule.setUpdator(sysUser.getId());
            enrollmentRule.setApplyId(enrollmentRuleVo.getApplyId());
            if(StringUtils.isNotBlank(enrollmentRuleVo.getCreateTime())){
                enrollmentRule.setCreateTime(DateUtil.parseDate(enrollmentRuleVo.getCreateTime()));
            }else{
                enrollmentRule.setCreateTime(DateUtil.parseDate(DateUtil.formatDate(new Date())));
            }
            enrollmentRuleDao.insert(enrollmentRule);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_INSERT);
        } else {
            EnrollmentRule enrollmentRule = enrollmentRuleDao.selectByPrimaryKey(enrollmentRuleVo.getId());
            enrollmentRule.setName(enrollmentRuleVo.getName());
            enrollmentRule.setUnit(enrollmentRuleVo.getUnit());
            enrollmentRule.setIntroduction(enrollmentRuleVo.getIntroduction());
            enrollmentRule.setUpdateTime(new Date());
            enrollmentRule.setUpdator(sysUser.getId());
            if(StringUtils.isNotBlank(enrollmentRuleVo.getCreateTime())){
                enrollmentRule.setCreateTime(DateUtil.parseDate(enrollmentRuleVo.getCreateTime()));
            }
            enrollmentRuleDao.updateByPrimaryKey(enrollmentRule);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
        }
    }

    /**
     * 根据条件逻辑删除
     *
     * @param enrollmentRuleVo 参数接受对象
     * @param sysUser          当前用户
     * @return ReturnResult
     * @author caideyong
     * @date 2019-11-22 16:21:03
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult remove(EnrollmentRuleVo enrollmentRuleVo, SysUser sysUser) {
        //要修改的字段
        EnrollmentRule enrollmentRule = new EnrollmentRule();
        enrollmentRule.setRemoveTag(DictCode.BASE_REMOVE_TAG_DELETE);
        enrollmentRule.setUpdator(sysUser.getId());
        enrollmentRule.setUpdateTime(new Date());
        //筛选条件
        Example example = new Example(EnrollmentRule.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(enrollmentRuleVo.getId())) {
            criteria.andIn("id", Arrays.asList(enrollmentRuleVo.getId().split(",")));
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        enrollmentRuleDao.updateByExampleSelective(enrollmentRule, example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 根据条件物理删除
     *
     * @param enrollmentRuleVo 参数接受对象
     * @param sysUser          当前用户
     * @return ReturnResult
     * @author caideyong
     * @date 2019-11-22 16:21:03
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult delete(EnrollmentRuleVo enrollmentRuleVo, SysUser sysUser) {
        //筛选条件
        Example example = new Example(EnrollmentRule.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(enrollmentRuleVo.getId())) {
            criteria.andIn("id", Arrays.asList(enrollmentRuleVo.getId().split(",")));
        }
        enrollmentRuleDao.deleteByExample(example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 导出数据
     *
     * @param response         响应对象
     * @param enrollmentRuleVo 传入参数对象
     * @return void
     * @author caideyong
     * @date 2019/11/27
     */
    @Override
    public void export(HttpServletResponse response, EnrollmentRuleVo enrollmentRuleVo) {
        List<EnrollmentRule> list = listExample(enrollmentRuleVo);
        EasyPoiUtil.exportExcel(list, "自主招生招生模板表", "招生模板", EnrollmentRule.class, "自主招生招生模板.xls", response);
    }


    /**
     * 导入招生章程
     *
     * @return ReturnResult
     * @author caideyong
     * @date 2019/11/27
     */
    @Override
    public ReturnResult importData(HttpServletRequest request, MultipartFile file, String catalog, String update, String applyId, SysUser sysUser) {
        // 1、不更新已存在数据，2、更新存在数据
        ReturnResult returnResult = sysFileService.fileUpload(file, request, catalog, BaseConstant.FILE_TYPE_EXECL);
        if (ErrorCode.CODE_0 == returnResult.getCode()) {
            String filePath = FilePathUtil.acceptCheckRealPath(request) + returnResult.getData().toString();
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            params.setNeedVerify(true);
            // 解决多读取问题，如果出现没有导入问题，需要将该属性去除
            params.setKeyIndex(0);
            // 如果有code码需要设置，现有bug，需要修改源码CellValueService
            params.setDictHandler(new GlobalExcelDictHandler());
            ExcelImportResult<EnrollmentRuleVerifyImportVo> result = ExcelImportUtil.importExcelMore(new File(filePath), EnrollmentRuleVerifyImportVo.class, params);
            List<EnrollmentRuleVerifyImportVo> educationUserImportList = result.getList();
            if (CollUtil.isNotEmpty(educationUserImportList)) {
                Map<String, EnrollmentRuleImportVo> educationUserMap = new HashMap<>();
                String key;
                for (EnrollmentRuleImportVo educationUser : educationUserImportList) {
                    key = educationUser.getName();
                    if (educationUserMap.keySet().contains(key)) {
                        continue;
                    }
                    educationUserMap.put(key, educationUser);
                }
                List<EnrollmentRule> enrollmentRuleList = new ArrayList<>();
                for (Map.Entry<String, EnrollmentRuleImportVo> entry : educationUserMap.entrySet()) {
                    // 名称不存在
                    EnrollmentRuleImportVo userFrom = entry.getValue();
                    EnrollmentRule enrollmentRule;
                    enrollmentRule = new EnrollmentRule();
                    enrollmentRule.setId(BaseUtil.uId());
                    enrollmentRule.setIntroduction(userFrom.getIntroduction());
                    enrollmentRule.setName(userFrom.getName());
                    enrollmentRule.setUnit(userFrom.getUnit());
                    enrollmentRule.setUseNum(0);
                    enrollmentRule.setApplyId(applyId);
                    enrollmentRule.setRemoveTag(BaseConstant.REMOVE_TAG_NO);
                    enrollmentRule.setCreator(sysUser.getId());
                    enrollmentRule.setUpdator(sysUser.getId());
                    enrollmentRule.setCreateTime(cn.hutool.core.date.DateUtil.date());
                    enrollmentRule.setUpdateTime(cn.hutool.core.date.DateUtil.date());
                    enrollmentRuleList.add(enrollmentRule);
                }
                // 保存
                if (enrollmentRuleList != null && enrollmentRuleList.size() > 0) {
                    this.insertList(enrollmentRuleList);
                }
            }else{
                // 行号从0开始，要加上titleRows和headRows
                if (result.isVerfiyFail()) {
                    // 如果错误，打印出提醒，直接返回
                    int successNum = 0;
                    int failNum = result.getFailList().size();
                    if (result.getList() != null && result.getList().size() > 0) {
                        successNum = result.getList().size();
                    }
                    String errorMsg = String.format("共导入%s条，成功%s条，失败%s条。", successNum + failNum, successNum, failNum);
                    List<EnrollmentRuleVerifyImportVo> failList = result.getFailList();
                    return new ReturnResult(ErrorCode.CODE_1, failList, errorMsg);
                }
            }
        }
        return returnResult;
    }

    @Override
    public void insertList(List<EnrollmentRule> enrollmentRules) {
        enrollmentRuleDao.insertList(enrollmentRules);
    }
}